package com.idcard.huashi;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;

import com.zysoft.function.ApiUtil;
import com.zysoft.function.SpecialAdapter;
import com.zysoft.function.Stroage;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Author : wmf
 * CreationTime : 2019/08/25
 * Description: 人员退场
 */
public class StaffExitFragment extends Activity {

    public static final int SUCCEED = 0;
    public static final int FAILE = 1;
    public static final int EXIT_SUCCEED = 2;
    public static final int EXIT_FAILE = 3;
    private String person_id = null;

    private EditText person_card;//输入框
    private TextView offline_data_submit;//离线提交数据
    private TextView update_data;//更新本地数据
    private TextView log_exit;//退出登录
    private TextView btn_center;//取消Alert
    private TextView Switch_project;//项目切换
    private TextView Staff_exit;//人员退场
    private TextView data_entry;//数据录入
    private TextView Power_off;//设备断电
    private TextView depart_data;//班组部门
    private Switch Switch_change;//退场事件
    private TextView Refresh;
    private  List<Map<String, Object>> mapList;
    private int num;
    private SpecialAdapter simpleAdapter;

    private ApiUtil apiUtil;
    private Stroage stroage;
    private Alert alert;
    private ArrayList<JSONObject> InfoData;
    private ArrayList<JSONObject> exitList;
    private View view;
    private ListView exit_list;
    private Util util;
    private Context mCtx;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mCtx = this;
        apiUtil = new ApiUtil();
        stroage = new Stroage();
        util = new Util();
        alert = new Alert();
        InfoData = new ArrayList<JSONObject>();
        setContentView(R.layout.activity_exit);
        person_card = findViewById(R.id.person_card);
        exit_list = findViewById(R.id.exit_list);
        apiUtil.ShowLoading("请求中...",mCtx);
        Ajax();
        initEnvet();
    }

    public void initEnvet() {
        View show = findViewById(R.id.img_btn);
        View back = findViewById(R.id.img_back);//回退按钮
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mCtx, IdcardFragment.class);
                startActivity(intent);
                finish();
            }
        });
        show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alert.ShowAlert();
            }
        });
        person_card.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                simpleAdapter.getFilter().filter(person_card.getText().toString().trim());
            }
        });
    }

    private void initView() {
       mapList = new ArrayList<Map<String, Object>>();
        try {
            JSONArray jsPerson = new JSONArray(exitList);
            for (int i = 0; i <jsPerson.length(); i++) {
                Map<String, Object> map = new HashMap<String, Object>();
                if(jsPerson.getJSONObject(i).getInt("peopleType") != 0 && jsPerson.getJSONObject(i).getInt("peopleType") != 3){
                    map.put("time", jsPerson.getJSONObject(i).getString("entryTime"));
                    map.put("name", jsPerson.getJSONObject(i).getString("teamName"));
                    map.put("person", jsPerson.getJSONObject(i).getJSONObject("workerInfo").getString("name"));
                    map.put("card", jsPerson.getJSONObject(i).getJSONObject("workerInfo").getString("idCardNumber"));
                    map.put("stats", "在岗");
                    map.put("oid",jsPerson.getJSONObject(i).getString("oid"));
                    mapList.add(map);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
         simpleAdapter = new SpecialAdapter(mCtx,
                mapList, R.layout.exit_item,
                new String[]{"time", "name", "person", "card", "stats","oid"},
                new int[]{R.id.personnel_item1, R.id.personnel_item2, R.id.personnel_item3, R.id.personnel_item4, R.id.personnel_item5,R.id.exit_id}
                );
        exit_list.setAdapter(simpleAdapter);
        exit_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                num = i;
                HashMap<String,Object> map = (HashMap<String,Object>) exit_list.getItemAtPosition(i);
                Log.e("zysoft", "你点击了第：" + i + exit_list.getItemAtPosition(i));
                util.ShowAlert(map.get("oid").toString());
            }
        });
    }
    @SuppressLint("HandlerLeak")
    public final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SUCCEED: {
                    try {
                        JSONObject json = new JSONObject(msg.obj.toString());
                        exitList = new ArrayList<JSONObject>();
                        if (json.has("code") && (json.getInt("code") == 200)) {
                            JSONObject js = json.getJSONObject("data");
                            Log.e("zysoft","获取当前项目人员在岗数量："+ js.getJSONArray("records").length());
                            for(int i = 0; i<js.getJSONArray("records").length();i++){
                                exitList.add(js.getJSONArray("records").getJSONObject(i));
                            }
                            Log.e("zysoft",exitList.toString());
                            Person(exitList.toString());
                        } else {
                            apiUtil.ShowToast(json.getString("msg"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    apiUtil.HideLoading();
                    break;
                }
                case FAILE: {
                    Log.e("zysoft", (String) msg.obj);
                    apiUtil.HideLoading();
                    apiUtil.ShowToast((String) msg.obj);
                    break;
                }
                case EXIT_SUCCEED: {
                    Log.e("zysoft", (String) msg.obj);
                    try {
                        JSONObject json = new JSONObject(msg.obj.toString());
                        if (json.has("code") && (json.getInt("code") == 200)) {
                            Log.e("zysoft", String.valueOf(num));
                            mapList.remove(num);
                            simpleAdapter.notifyDataSetChanged();
                            exit_list.invalidate();
                            apiUtil.ShowToast("退场成功");
                        }else {
                            apiUtil.ShowToast(json.getString("msg"));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    apiUtil.HideLoading();
                    util.HideAlert();
                    break;
                }
                case EXIT_FAILE: {
                    apiUtil.ShowToast("退场失败，请稍后再试");
                    apiUtil.HideLoading();
                    Switch_change.setChecked(false);
                    break;
                }
            }
        }
    };
   private void Person(String data){
       Log.e("zysoft_data",data);
       if(data.length()==0){
           apiUtil.ShowToast("暂无数据，请联系后台人员");
           return;
       }
       initView();
   }
    private class Util {
        private TextView PersonName;//姓名
        private TextView corpName;//分包商名称
        private TextView workTeamName;//作业队名称
        private TextView cardNumber;//安全帽标识
        private TextView teamName;//班组名称
        private TextView name;//所在企业
        private TextView idCardNumber;//证件号码
        private TextView entryTime;//进场时间
        private TextView cellPhone;//联系电话
        private TextView status;//人员状态
        private TextView workerType;//人员类型
        private TextView operating;//非 一般工人
        private TextView center_show;//取消

        LayoutInflater inflater = LayoutInflater.from(mCtx);
        View view = inflater.inflate(R.layout.project_show_dialog, null);

        AlertDialog.Builder builder = new AlertDialog.Builder(mCtx);
        Dialog dialog = builder.create();
        public void ShowAlert(String id) {
            dialog.getWindow().setGravity(Gravity.BOTTOM);//可以设置显示的位置
            dialog.show();
            PersonName =  view.findViewById(R.id.PersonName);
            corpName = view.findViewById(R.id.corpName);
            workTeamName = view.findViewById(R.id.workTeamName);
            cardNumber =  view.findViewById(R.id.cardNumber);
            teamName = view.findViewById(R.id.teamName);
            name =  view.findViewById(R.id.name);
            idCardNumber =  view.findViewById(R.id.idCardNumber);
            entryTime = view.findViewById(R.id.entryTime);
            cellPhone = view.findViewById(R.id.cellPhone);
            status =  view.findViewById(R.id.status);
            workerType =  view.findViewById(R.id.workerType);
            Switch_change =  view.findViewById(R.id.Switch_change);
            operating = view.findViewById(R.id.operating);
            center_show =  view.findViewById(R.id.center_show);
            center_show.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    HideAlert();
                }
            });
            Switch_change.setChecked(false);
            try {
                JSONArray JsonData = new JSONArray(exitList);
                for(int i = 0;i<JsonData.length();i++){
                    if(JsonData.getJSONObject(i).getString("oid") == id){
                        Log.e("zysoft",JsonData.getJSONObject(i).getJSONObject("workerInfo").getString("idCardNumber"));
                        Log.e("zysoft",JsonData.getJSONObject(i).toString());
                        PersonName.setText(JsonData.getJSONObject(i).getJSONObject("workerInfo").getString("name"));
                        corpName.setText(JsonData.getJSONObject(i).getString("corpName"));
                        workTeamName.setText(JsonData.getJSONObject(i).getString("workTeamName"));
                        cardNumber.setText(JsonData.getJSONObject(i).getString("cardNumber"));
                        idCardNumber.setText(JsonData.getJSONObject(i).getJSONObject("workerInfo").getString("idCardNumber"));
                        teamName.setText(JsonData.getJSONObject(i).getString("teamName"));
                        name.setText(JsonData.getJSONObject(i).getJSONObject("workerInfo").getJSONObject("corpBasicInfo").getString("corpName"));
                        entryTime.setText(JsonData.getJSONObject(i).getString("entryTime"));
                        person_id = JsonData.getJSONObject(i).getString("oid");
                        Log.e("zysoft",person_id);
                        status.setText("在岗");
                        cellPhone.setText(JsonData.getJSONObject(i).getJSONObject("workerInfo").getString("cellPhone"));
                        switch (JsonData.getJSONObject(i).getInt("peopleType")){
                            case 1:{
                                workerType.setText("班组长");
                                Switch_change.setVisibility(View.GONE);
                                operating.setVisibility(View.VISIBLE);
                                break;
                            }
                            case 2:{
                                workerType.setText("一般工人");
                                Switch_change.setVisibility(View.VISIBLE);
                                operating.setVisibility(View.GONE);
                                break;
                            }
                        }
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                apiUtil.ShowToast("数据解析失败");
            }
            //工人退场
            Switch_change.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                    if (isChecked) {
                        apiUtil.ShowLoading("退场中...",mCtx);
                        Exit(person_id);
                    }
                }
            });
            Window window = dialog.getWindow();
            WindowManager.LayoutParams lp = window.getAttributes();
            WindowManager windowManager = getWindowManager();
            Display display = windowManager.getDefaultDisplay();
            lp.width = display.getWidth();
            dialog.getWindow().setAttributes(lp);
            dialog.getWindow().setContentView(view);//自定义布局应该在这里添加，要在dialog.show()的后面
        }
        public void HideAlert() {
            dialog.dismiss();
        }

    }
    private void Ajax(String... params) {
        OkHttpClient client = new OkHttpClient.Builder()//创建OkHttpClient对象。
                .connectTimeout(20, TimeUnit.SECONDS)//连接超时时间
                .readTimeout(20,TimeUnit.SECONDS)//读取超时时间
                .build();
        RequestBody requestBody = new FormBody.Builder()
                .add("pageSize","99999")
                .add("projectCode", stroage.getCode(mCtx).toString())//查询所在项目下面的人员
                .add("status","1")//查询在岗
                .build();
        Request request = new Request.Builder()
                .url(apiUtil.ExitPerson)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e("zysoft", "responseCode" + "   " + response.code() + "responseMessage" + response.message());
                mHandler.sendMessage(mHandler.obtainMessage(SUCCEED, response.body().string()));
            }
            @Override
            public void onFailure(Call call, IOException e) {
                if(e instanceof SocketTimeoutException){
                    mHandler.sendMessage(mHandler.obtainMessage(FAILE, "请求超时"));
                }else {
                    mHandler.sendMessage(mHandler.obtainMessage(FAILE, "连接异常"));
                }
                Log.e("zysoft", "onFailure: " + e.getMessage());
            }
        });

    }

    private void Exit(String id) {
        OkHttpClient client = new OkHttpClient.Builder()//创建OkHttpClient对象。
                .connectTimeout(20, TimeUnit.SECONDS)//连接超时时间
                .readTimeout(20,TimeUnit.SECONDS)//读取超时时间
                .build();
        RequestBody requestBody = new FormBody.Builder()
                .add("id", id)
                .build();
        Request request = new Request.Builder()
                .url(apiUtil.ExitUrl)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e("zysoft", "responseCode" + "   " + response.code() + "responseMessage" + response.message());
                mHandler.sendMessage(mHandler.obtainMessage(EXIT_SUCCEED, response.body().string()));
            }
            @Override
            public void onFailure(Call call, IOException e) {
                if (e instanceof SocketTimeoutException) {
                    mHandler.sendMessage(mHandler.obtainMessage(EXIT_FAILE, "请求超时"));
                } else {
                    mHandler.sendMessage(mHandler.obtainMessage(EXIT_FAILE, "连接异常"));
                }
                Log.e("zysoft", "onFailure: " + e.getMessage());
            }
        });
    }
    public class Alert implements View.OnClickListener {

        LayoutInflater inflater = LayoutInflater.from(mCtx);
        View show = inflater.inflate(R.layout.show_dialog, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(mCtx);
        Dialog dialog = builder.create();

        public void ShowAlert() {
            dialog.show();
            Window window = dialog.getWindow();
            WindowManager.LayoutParams lp = window.getAttributes();
            WindowManager windowManager = getWindowManager();
            Display display = windowManager.getDefaultDisplay();
            lp.width = display.getWidth();
            dialog.getWindow().setAttributes(lp);
            dialog.getWindow().setGravity(Gravity.BOTTOM);//可以设置显示的位置
            dialog.getWindow().setContentView(show);//自定义布局应该在这里添加，要在dialog.show()的后面

            offline_data_submit = show.findViewById(R.id.offline_data_submit);//离线提交
            update_data =show.findViewById(R.id.update_data);//更新本地数据
            Switch_project =  show.findViewById(R.id.Switch_project);//切换项目
            Staff_exit = show.findViewById(R.id.Staff_exit);//人员退场
            log_exit =  show.findViewById(R.id.log_exit);//退出登录
            data_entry = show.findViewById(R.id.data_entry);//进场数据录入
            depart_data =  show.findViewById(R.id.depart_data);//班组部门
            Power_off = show.findViewById(R.id.Power_off);//设备断电
            btn_center =  show.findViewById(R.id.btn_center);//取消
            Refresh = show.findViewById(R.id.Refresh);//刷新
            offline_data_submit.setVisibility(View.GONE);
            update_data.setVisibility(View.GONE);
            Staff_exit.setVisibility(View.GONE);
            Power_off.setVisibility(View.GONE);
            Refresh.setVisibility(View.VISIBLE);
            //监听事件
            offline_data_submit.setOnClickListener(this);
            update_data.setOnClickListener(this);
            Switch_project.setOnClickListener(this);
            data_entry.setOnClickListener(this);
            depart_data.setOnClickListener(this);
            log_exit.setOnClickListener(this);
            Power_off.setOnClickListener(this);
            btn_center.setOnClickListener(this);
            Refresh.setOnClickListener(this);

        }
        public void HideAlert() {
            dialog.dismiss();
        }

        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.Switch_project://项目切换
                    HideAlert();
                    Intent intent = new Intent(mCtx, ProjectFragment.class);
                    startActivity(intent);
                    finish();
                    break;
                case R.id.data_entry://数据录入
                    HideAlert();
                    Intent per = new Intent(mCtx, IdcardFragment.class);
                    startActivity(per);
                    finish();
                    break;
                case R.id.depart_data://班组操作
                    HideAlert();
                    Intent tem = new Intent(mCtx, TeamFragment.class);
                    startActivity(tem);
                    finish();
                    break;
                case R.id.log_exit:
                    Log.e("zysoft", "你点击了退出当前项目按钮");
                    HideAlert();
                    Intent exit = new Intent(mCtx, MainActivity.class);
                    startActivity(exit);
                    finish();
                    break;
                case R.id.Power_off:
                    HideAlert();
                    break;
                case R.id.btn_center:
                    Log.e("zysoft", "你点击了取消按钮");
                    HideAlert();
                    break;
                case R.id.Refresh:
                    Log.e("zysoft", "你点击了刷新按钮");
                    HideAlert();
                    apiUtil.ShowLoading("刷新中...",mCtx);
                    Ajax();
                    break;
            }
        }
    }
}
